import MYSQLUtils

mdFilePath: str = "D:/code/笔记/唯智/项目/bmwms/输出文档/八马数据字典.md"


def subStrByStartAndEnd(content: str, start: str, end: str, vernier: int = 0) -> str:
    """
    从一个字符串中范围截取字符
    :param content: 字符串
    :param start:   起始字符串
    :param end:     结束字符串
    :param vernier: 开始位置
    :return:
    """
    contentTemp = content[vernier:]
    strtemp = contentTemp[contentTemp.find(start) + len(start):]
    if end is None:
        tableStr: str = strtemp
    else:
        tableStr: str = strtemp[:strtemp.find(end)]
    return tableStr


if __name__ == '__main__':
    # 游标
    vernier = 0
    while vernier != -1:
        # 加载md文件
        mdFile = open(mdFilePath, encoding="utf-8", mode="r")
        markdown: str = mdFile.read()
        mdFile.close()
        # 获取一个表的字符串
        tableStr = subStrByStartAndEnd(markdown, "##", "##", vernier)
        # 如果这个表已经添加过,那么掠过
        if tableStr.find("|字段名|描述|\n|----|----|") == -1:
            vernier += len(tableStr)
        # 否则替换
        else:
            newTableStr = tableStr.replace("|字段名|描述|\n|----|----|", "|字段名|描述|类型|\n|----|----|----|")
            # 使用换行符分解成list
            attrList: list = newTableStr.split("\n")
            # 获取表名
            tableName: str = subStrByStartAndEnd(attrList[0], ":", " ", 0)
            # 处理每行
            for index, attr in enumerate(attrList):
                if index > 2 and attr != "":
                    attrName = subStrByStartAndEnd(attr, "|", "|", 0)
                    attrType = MYSQLUtils.getAllAttrTypeAndSizeByTableNameAndAttrName(tableName, attrName)[0][0]
                    attrList[index] = attr + attrType + "|"
            newTableStr = "\n".join(attrList)
            markdown = markdown.replace(tableStr, newTableStr)
            mdFile = open(mdFilePath, encoding="utf-8", mode="w")
            mdFile.write(markdown)
            mdFile.close()
            print("已转换:"+tableName)
